import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, DatePicker } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import router from 'umi/router';
import AuthComponent from '@/components/Authorized/AuthComponent';
import { fileDownload } from '@/utils/downExcel';
import { pkgExpressOrderPage, exportPkgExpressOrder } from './service';
import moment from 'moment';

import { Const } from '../Const';

// 变量
let hiddenData = {}

const ExpressInquiry = () => {

  const actionRef = useRef();
  const ref = useRef()

  // 表格高度
  const [height, controlH] = useState(300)
  const [isCollapse, controlC] = useState(true);
  // 保存搜索数据
  const [searchData, handleSearchData] = useState({})
  // 导出按钮Loading
  const [loading, handleLoading] = useState(false)
  // 表格是否有数据
  const [exportFlag, handleExportFlag] = useState(false)

  // 导出接口
  const { run: exportPkgExpressOrderR } = useRequest(params => exportPkgExpressOrder(params), {
    manual: true,
    onSuccess: (data) => {
      fileDownload(
        data,
        '快递单信息数据.xlsx'
      );
      handleLoading(false)
    }
  })

  // 点击搜索
  const beforeSearchSubmit = params => {
    let arr = ['flightDate', 'createTime'];
    for (let item of arr) {
      if (params[item] && params[item].isValid()) {
        params[item] = moment(params[item]).format('YYYY-MM-DD')
      }
    }
    if (!isCollapse) {
      handleSearchData(params)
      return params
    } else {
      if (event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('expressOrderId') === -1) {
          params.expressOrderId = ''
        }
        if (Object.keys(params).indexOf('accidentId') === -1) {
          params.accidentId = ''
        }
        if (Object.keys(params).indexOf('flightDate') === -1) {
          params.accidentId = ''
        }
        handleSearchData({ ...hiddenData, ...params })
        return { ...hiddenData, ...params }
      } else if (event.target.querySelector('span').innerText === '重 置') {
        handleSearchData({})
        hiddenData = {}
        return params
      }
    }
  }

  // 跳转事故单详情
  const goToDetail = (item) => {
    let ownerType
    if (item.accidentType === '1') {
      ownerType = 1
    } else if (item.accidentType === '2') {
      ownerType = 2
    } else if (item.accidentType === '3') {
      ownerType = 3
    } else if (item.accidentType === '6') {
      ownerType = 6
    } else if (item.accidentType === '7') {
      ownerType = 7
    }
    router.push({
      pathname: '/banksearchSystem/inPortBaggageManagement/accidentDetail',
      state: {
        accidentId: item.accidentId,
        ownerType: ownerType
      }
    })
  }

  // 导出
  const exportCharts = () => {
    if (!exportFlag) {
      message.warning('表格数据为空');
    } else {
      handleLoading(true)
      exportPkgExpressOrderR(searchData)
    }
  };

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 440);
    } else {
      controlH(document.body.clientHeight - 512);
    }
  }, [isCollapse])

  // 切换tab清空搜索
  useEffect(() => {
    hiddenData = {}
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const columns = [
    {
      title: '快递单号',
      dataIndex: 'expressOrderId',
      width: 150
    },
    {
      title: '单据编号',
      dataIndex: 'accidentId',
      width: 120,
      render: (text, record) => (
        <span
          style={{cursor:"pointer"}}
          // disabled={!AuthComponent.getAuth(Const.permissionsType.get(+record.accidentType) + '.basicPermissions')}
          onClick={() => goToDetail(record)}
        >{text}</span>
      ),
      ellipsis: true
    },
    {
      title: '处理类型',
      dataIndex: 'accidentType',
      width: 120,
      render: (text, _) => (
        <div>
          {text === '1' || text === '7' ? '破损行李' : null}
          {text === '2' ? '少收行李' : null}
          {text === '3' ? '多收行李' : null}
          {text === '4' ? '异常行李' : null}
          {text === '6' ? '遗失行李' : null}
        </div>
      ),
      hideInSearch: true
    },
    {
      title: '旅客姓名',
      dataIndex: 'paxName',
      width: 120,
      hideInSearch: true
    },
    {
      title: '证件号',
      dataIndex: 'idNo',
      width: 180,
      hideInSearch: true
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 120,
      hideInSearch: true
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
    },
    {
      title: '始发站',
      dataIndex: 'org',
      width: 120,
      hideInSearch: true
    },
    {
      title: '收件人',
      dataIndex: 'expressRecipient',
      width: 120
    },
    {
      title: '收件人电话1',
      dataIndex: 'recipientPhoneFirst',
      width: 120
    },
    {
      title: '收件人电话2',
      dataIndex: 'recipientPhoneSecond',
      width: 120
    },
    {
      title: '收件人地址',
      dataIndex: 'recipientAddress',
      width: 120,
      hideInSearch: true,
      ellipsis: true
    },
    {
      title: '录入时间',
      dataIndex: 'createTime',
      width: 120,
      ellipsis: true,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
    },
    {
      title: '录入人',
      dataIndex: 'createUser',
      width: 120,
      ellipsis: true
    },
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.expressInquiry}
        headerTitle={
          <div>
            <span style={{ fontWeight: "700", color: "rgba(0,0,0,0.85)", fontSize: '16px' }}>快递数据列表</span>
          </div>
        }
        options={{ fullScreen: true, reload: false, setting: true, density: false }}
        // beforeSearchSubmit={beforeSearchSubmit}
        search={{
          span: 6,
          onCollapse: val => {
            controlC(val)
            // if (!val && hiddenData) {
            //   ref.current.setFieldsValue({
            //     recipientPhoneFirst: hiddenData.recipientPhoneFirst,
            //     recipientPhoneSecond: hiddenData.recipientPhoneSecond
            //   })
            // } else {
            //   hiddenData = ref.current.getFieldsValue()
            // }
          }
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode='InformationService.expressInquiry.basic'>
            <Button type="primary" onClick={() => exportCharts()} loading={loading} size="small">
              导出excel
            </Button>
          </AuthComponent>
        ]}
        tableAlertRender={false}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          let arr = ['flightDate', 'createTime'];
          for (let item of arr) {
            if (params[item] && params[item].isValid()) {
              params[item] = moment(params[item]).format('YYYY-MM-DD')
            }
          }
          handleSearchData(params);
          return pkgExpressOrderPage(params);
        }}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 900, y: height }}
      />
    </>
  );
};

export default Form.create()(ExpressInquiry);
